package util;

import com.mysql.cj.jdbc.Driver;

import java.sql.PreparedStatement;
import java.sql.*;

/**
 * Java Database Connectivity，数据库连接工具
 */
public class JDBCUtil {

    public void getConnection(String sql){

        try {
            // 通过反射将厂商提供的数据库驱动加载到程序
            //1.注册驱动  --- 要在 tomCat 的 lib 目录下面添加驱动包
            DriverManager.registerDriver(new Driver());
            //  Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取数据库连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

            //3.创建Statement对象 其实就是 sql 语句发送给mySql
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            //4.编写SQL语句并执行，获取结果
            // resultSet 是执行结果的集合
            ResultSet resultSet = preparedStatement.executeQuery();


            //5.处理结果
            while (resultSet.next()) {
                int uid = resultSet.getInt("uid");
                String username = resultSet.getString("user_name");
                String userPwd = resultSet.getString("user_pwd");
                System.out.println(uid + "\t" + username + "\t" + userPwd);
            }

            //6.释放资源(先开后关原则)
            resultSet.close();
            preparedStatement.close();
            connection.close();


        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }

    public void closeResultSet(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection ){

        try {
            //6.释放资源(先开后关原则)
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }catch (Exception e){
            System.out.println("关闭数据库连接资源异常-----");
        }

    }
}
